package TestDemo.example.aop;

import TestDemo.example.mapper.OperateLogMapper;
import TestDemo.example.pojo.OperateLog;
import TestDemo.example.utils.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import java.time.LocalDateTime;

@Slf4j
@Component
@Aspect
public class OperateLogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("execution(* TestDemo.example.controller.*.update*(..)) || " +
            "execution(* TestDemo.example.controller.*.add*(..)) || " +
            "execution(* TestDemo.example.controller.*.delete*(..))")
    public Object logAspect(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        log.info("正在计时");
        long begin = System.currentTimeMillis();
        Object result=proceedingJoinPoint.proceed();
        long end = System.currentTimeMillis();
        long costTime = end-begin;
        log.info("方法耗时：{}",costTime);

        OperateLog operateLog = new OperateLog();
        operateLog.setOperateEmpId(CurrentHolder.getCurrentId());
        operateLog.setOperateTime(LocalDateTime.now());
        operateLog.setCostTime(costTime);
        operateLog.setClassName(proceedingJoinPoint.getTarget().getClass().getName());
        operateLog.setMethodName(proceedingJoinPoint.getSignature().getName());
        operateLog.setMethodParams(proceedingJoinPoint.getArgs().toString());
        operateLog.setReturnValue(result.toString());

        log.info("记录操作日志：{}",operateLog);
        operateLogMapper.add(operateLog);
        return result;
    }



}
